package com.yhq.yhqproject.base.modules.board.service;

import com.yhq.yhqproject.base.common.utils.AIStringUtil;
import com.yhq.yhqproject.base.common.utils.IdGen;
import com.yhq.yhqproject.base.common.utils.ObjUtil;
import com.yhq.yhqproject.base.common.web.ListByPageResp;
import com.yhq.yhqproject.base.modules.board.entity.AiTemplate;
import com.yhq.yhqproject.base.modules.board.entity.dto.CreatePromptReq;
import com.yhq.yhqproject.base.modules.board.entity.dto.ListTemplateReq;
import com.yhq.yhqproject.base.modules.board.entity.dto.TemplateAddDTO;
import com.yhq.yhqproject.base.modules.board.entity.dto.TemplateUpdateDTO;
import com.yhq.yhqproject.base.modules.board.repo.AiTemplateRepo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AiTemplateService {

    @Resource
    private AiTemplateRepo templateRepo;
    @Resource
    private MongoTemplate mongoTemplate;


    public String add(TemplateAddDTO dto) {
        AiTemplate old = templateRepo.findAiTemplateByTitle(dto.getTitle());
        if (old == null) {
            old = new AiTemplate();
            BeanUtils.copyProperties(dto, old);
            old.setId(IdGen.get().nextSid());
            old.setCreateTime(new Date());
            old.setUpdateTime(new Date());
            int cnt = AIStringUtil.countSubstring(dto.getContent(), "%s");
            old.setParamsCount(cnt);
            old.setStatus(0);
            templateRepo.insert(old);
            return "1";
        }
        throw new RuntimeException("title existed");
    }


    public String delete(String id) {
        templateRepo.deleteById(id);
        return "1";
    }


    public String update(TemplateUpdateDTO dto) {
        int cnt = AIStringUtil.countSubstring(dto.getContent(), "%s");
        Update update = new Update();
        Map<String, Object> map = ObjUtil.beanAttrToMapKV(dto);
        for (Map.Entry<String, Object> e : map.entrySet()) {
            if ("id".equals(e.getKey())) {
                continue;
            }
            update.set(e.getKey(), e.getValue());
        }
        update.set("updateTime", new Date());
        update.set("paramsCount", cnt);
        update.set("status", 2);
        mongoTemplate.updateFirst(new Query(Criteria.where("id").is(dto.getId())), update, AiTemplate.class);
        return "1";
    }


    public AiTemplate query(String id) {
        AiTemplate m = templateRepo.findById(id).get();
        return m;
    }


    public AiTemplate queryByTitle(String title) {
        return templateRepo.findAiTemplateByTitle(title);
    }


    public ListByPageResp<AiTemplate> list(ListTemplateReq req) {
        Criteria criteria = null;
        if (req.getSubject() != null && req.getSubject().length() > 0) {
            if (criteria == null) {
                criteria = Criteria.where("subject").regex(req.getSubject());
            } else {
                criteria = criteria.and("subject").regex(req.getSubject());
            }
        }
        if (req.getTitle() != null && req.getTitle().length() > 0) {
            if (criteria == null) {
                criteria = Criteria.where("title").regex(req.getTitle());
            } else {
                criteria = criteria.and("title").regex(req.getTitle());
            }
        }
        if (req.getScene() != null && req.getScene().length() > 0) {
            if (criteria == null) {
                criteria = Criteria.where("scene").regex(req.getScene());
            } else {
                criteria = criteria.and("scene").regex(req.getScene());
            }
        }

        Query query = new Query();
        if (criteria != null) {
            query = new Query(criteria);
        }

        long all = mongoTemplate.count(query, AiTemplate.class);
        query.with(Sort.by(Sort.Direction.DESC, "createTime"));
        query.skip((req.getPage() - 1) * req.getSize());
        query.limit(req.getSize());
        List<AiTemplate> list = mongoTemplate.find(query, AiTemplate.class);
        //
        ListByPageResp<AiTemplate> resp = new ListByPageResp<>();
        resp.setData(list);
        resp.setTotal(all);
        resp.setPage(req.getPage());
        resp.setSize(req.getSize());
        return resp;
    }

    public String createPrompt(CreatePromptReq req) {
        AiTemplate m = templateRepo.findAiTemplateByTitle(req.getTitle());
        String prompt = String.format(m.getContent(), req.getParams().toArray());
        return prompt;
    }
}
